layui.use(['layer', 'commons', 'form', 'laytpl', 'laydate', 'element', 'table', 'laypage'], function() {
	var layer = layui.layer,
		$ = layui.jquery,
		common = layui.commons,
		form = layui.form,
		laydate = layui.laydate,
		laytpl = layui.laytpl,
		table = layui.table,
		laypage = layui.laypage,
		element = layui.element;

	// 默认参数
	var isprint = "2";
	var currPage = "1";
	var keyword = "";
	var wardId = getUser().wardId;
console.log(wardId)
	//监听提交
	form.on('submit(findwd)', function(data) {
		console.log(data.field);
		isprint = data.field.interest;
		keyword = data.field.keyword;
		selectPrintList(isprint,currPage,keyword)
		return false;
	});

	//表格复选框监听
	var isSelect = 0;
	table.on('checkbox(test)', function(obj) {
		console.log(obj);
		var input = $('.layui-table tbody input');
		var n = 1;
		for (var i = 0; i < input.length; i++) {
			if ($(input[i]).is(':checked')) {
				n++
			}
		}
		//$('.num').text(n>10?(n-1)/2:n-1)
		//避免点击全选之后出现没有选中仍然显示有一个被选中
		if (obj.type == 'all') {
			//全选
			if (isSelect === 0) {
				isSelect = 1;
				$('.num').text(n > 10 ? n - 1 : n);
				//取消全选
			} else if (isSelect === 1) {
				isSelect = 0;
				$('.num').text(0);
			}
		} else {
			$('.num').text(n - 1);
		}
	});

	//执行打印
	function executePrint(ids) {
		common.ajax('/service-patient/patient/executePrint', JSON.stringify({
			"body": {
				// "ids": "5,6,9"
				"ids": ids
			},
			"header": {},
			"token": {}
		}), function(data) {
			console.log(data);
		}, 'post');
	}


	//中文字符处理
	function toUtf8(str) {
		var out, i, len, c;
		out = "";
		len = str.length;
		for (i = 0; i < len; i++) {
			c = str.charCodeAt(i);
			if ((c >= 0x0001) && (c <= 0x007F)) {
				out += str.charAt(i);
			} else if (c > 0x07FF) {
				out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
				out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
				out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
			} else {
				out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
				out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
			}
		}
		return out;
	}

	//生成二维码
	function outputQRCod(txt, width, height, obj) {
		//中文格式转换
		// var str = toUtf8(txt);
		console.log(txt);
		//生成二维码
		obj.qrcode({
			render: "canvas",
			width: width,
			height: height,
			text: txt
		});
	}

	// 生成一维码
	// function fn(id) {
	// 	$("#bcTarget").barcode(id, "code128");
	// }

	//头工具栏事件
	table.on('toolbar(test)', function(obj) {
		console.log(obj);
		var checkStatus = table.checkStatus(obj.config.id).data;
		console.log(checkStatus);

		// 打印预览
		var getTpl = demo2.innerHTML,
			view = document.getElementById('view2');
		laytpl(getTpl).render(checkStatus, function(html) {
			view.innerHTML = html;
		});

		var workid = '';
		for (var i = 0; i < checkStatus.length; i++) {
			workid = workid + checkStatus[i].patientId + ','
		}
		workid = workid.substr(0, workid.length - 1);
		console.log(workid);
		if (checkStatus.length > 0) {
			// 查询打印要展示的患者信息 printType : 1:床头卡  2:腕带
			common.ajax('/service-patient/patient/selectPrintInfoList', JSON.stringify({
				"body": {
					"wardId": wardId,
					"patientIds": workid,
					"printType": 1
				},
				"header": {},
				"token": {}
			}), function(data) {
				console.log(data.data[0].printId);
				//todo...
				//把printId 传参给executePrint()
				var arr = [];
				var bctargets = $(".bcTarget");
				for (var i = 0; i < data.data.length; i++) {
					arr.push(data.data[i].printId);
					//生成二维码
					// bctargets.eq(i).barcode(data.data[i].patientId, "code128", {
					// 	barWidth: 2,
					// 	barHeight: 30,
					// 	showHRI: true
					// });
					console.log(bctargets.eq(i));
					console.log(data.data[i].patientId);
					var pat = data.data[i].patientId.toString();
					outputQRCod(pat, 100, 100, bctargets.eq(i))
				}

				var ids = arr.toString();
				var mylay = layer.open({
					type: 1,
					// area: '500px',
					content: $('#preview'),
					btn: ['确定打印', '取消'],

					yes: function() {
						console.log("执行打印");
						layer.msg('正在执行打印');

						//调用浏览器打印功能
						$("#preview").jqprint();

						executePrint(ids);
						layer.close(mylay)
					},
					no: function() {
						console.log("关闭打印");
					}
				});
			}, 'post');
		} else {
			layer.msg('至少需要勾选一项', {
				icon: 5
			})
		}
	});



	// 获取打印列表（床头卡、腕带）
	function selectPrintList(isprint, currPage) {
		var param = JSON.stringify({
			"body": {
				"wardId": wardId,
				"keyword": keyword,
				"printState": isprint,
				"currPage": currPage
			},
			"header": {},
			"token": {}
		});



		console.log(isprint);
		$.ajax({
			'type': 'post',
			'url': '/service-patient/patient/selectPrintList',
			'data': param,
			'dataType': 'json',
			'contentType': "application/json",
			'success': function(data) {
				console.log(data);
				console.log(data.data.total);
				var len = data.data.total;
				//表格
				table.render({
					elem: '#demo',
					//height: 315,
					toolbar: '#toolbarDemo',
					defaultToolbar:'print',  //头部功能显示
					// page: true, //一次请求全部数据前端自动分页
					cols: [
						[{type:'checkbox'},
						{field:'bedCode',title:'床号'},
						{field:'patName',title:'姓名'},
						{field:'patSex',title:'性别'},
						{field:'patAge',title:'年龄'},
						{field:'patientStatus',title:'病情状态'},
						{field:'illnessState',title:'病情'},
						{field:'diet',title:'住院号'},
						{field:'isolation',title:'隔离'},
						{field:'nursingLevel',title:'护理级别'},
						{field:'diatag',title:'诊断信息'},
						{field:'respNurse',title:'责任护士'},
						{field:'admDate',title:'入院日期'},
						{field:'printCount',title:'打印次数'},
						{field:'lastPrintTime',title:'最后一次打印时间'},
						{field:'patAge',title:'饮食'}]
					],
					data: data.data.list
				});

				//分页监听
				laypage.render({
					elem: 'test2',
					count: len, //数据总数，从服务端得到
					curr: 1, //起始页
					// groups: 5,
					limit: 10,
					limits: [10],
					layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
					jump: function(obj, first) {
						//obj包含了当前分页的所有参数，比如：
						console.log("当前页码" + obj.curr); //得到当前页，以便向服务端请求对应页的数据。
						console.log("当前显示" + obj.limit + "条"); //得到每页显示的条数
						//根据当前页请求和渲染模
						currPage = obj.curr
						//首次不执行
						if (!first) {
							//do something  isprint1：未打印    2：已打印
							selectPrintList(isprint, currPage)
						}
					}
				});
			},
			'error': function(res) {
				console.log(res);
			}
		});
	}

	selectPrintList(isprint, currPage)
})
